/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package model.DAO;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import javax.ejb.Stateful;
import javax.persistence.EntityManager;
import javax.persistence.EntityNotFoundException;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import model.dto.ApplicationDTO;
import model.dto.AvailabilityDTO;
import model.dto.CompetenceDTO;
import model.dto.CompetenceProfileDTO;
import model.dto.PersonDTO;
import model.integration.Person;
import model.integration.Application;
import model.integration.Availability;
import model.integration.Competence;
import model.integration.CompetenceList;
import model.integration.CompetenceProfile;
import model.integration.DateList;


/**
 *
 * @author Ahmed Salem
 */
@Stateful
public class Logic {
@PersistenceContext(unitName="iv1201-projectPU")
private EntityManager em;
List<CompetenceProfileDTO> comp ; 

    /**
     *
     * @return a list of all applications when called from control is made
     */
    @SuppressWarnings("empty-statement")
    public List<ApplicationDTO>getMyApplication(){
                   String personQuery = "SELECT u FROM Person u WHERE u.roleId = 2";
                   List<ApplicationDTO> apdto = new ArrayList <ApplicationDTO>();
                   List<PersonDTO> p = em.createQuery(personQuery).getResultList();
                   List<DateList> dl = new LinkedList <DateList>();   
                   List<CompetenceList> cl  = new LinkedList<CompetenceList>();
                 
                   CompetenceList clo; 
                   Application ap;
                   DateList dlo ;
        
                   
                   for(int i = 0; i < p.size(); i++){
                       ap=  new Application();
                       dlo = new DateList();
                       clo = new CompetenceList();
                       
                       
                       ap.setName(p.get(i).getName());
                       ap.setSurname(p.get(i).getSurname());
                       ap.setSSN(p.get(i).getSsn());
                       ap.setEmail(p.get(i).getEmail());
                       for(int j = 0; j <findAvailability(p.get(i).getPersonId()).size();j++)
                        {
                             dlo.setFromDate(findAvailability(p.get(i).getPersonId()).get(j).getFromDate()); // new 
                             dlo.setToDate(findAvailability(p.get(i).getPersonId()).get(j).getToDate()); // new 
                             dl.add(dlo);
                        }
                       ap.setDateList(dl);
                       for(int k = 0; k < findCompetenceProfile(p.get(i).getPersonId()).size();k++)
                       {
                            clo.setCompetence(findCompetence(findCompetenceProfile(p.get(i).getPersonId()).get(k).getCompetenceId()).getName());
                            clo.setYearsofExp(findCompetenceProfile(p.get(i).getPersonId()).get(k).getYearsOfExperience());
                            cl.add(clo);
      
                       }
                       ap.setCompetence(cl);
                       
                       apdto.add(i, ap);
                   }return apdto; 
                 
            

    }


    /**
     *
     * @param application
     * @return a boolean when application is created
     */
    public boolean createApplication(Application ap){
        System.out.println("Logic");

        Person p = null;
        Availability av = null ; 
        Competence co = null; 
        CompetenceProfile cp = null; 
        List<CompetenceList> cl = ap.getCompetence();
   try{
       // Create instance of each object 
        p = new Person();
        av = new Availability();
        co = new Competence();
        cp = new CompetenceProfile();
        
        // Create the person first 
        p.setName(ap.getName());
        p.setSurname(ap.getSurname());
        p.setSsn(ap.getSSN());
        p.setEmail(ap.getEmail());
        p.setRoleId(2);
        em.persist(p);
        em.flush();
        em.refresh(p);
        // Create the Availability
        
        av.setPersonId(p.getPersonId());
        av.setFromDate(ap.getFromDate());
        av.setToDate(ap.getToDate());
        em.persist(av);
        em.flush();
        em.refresh(av);
        
        // Create the Competence 
        for(int i = 0 ; i < ap.getCompetence().size() ; i++ )
        {   
         co.setName(ap.getCompetence().get(i).getCompetence());
        
        }
        em.persist(co);
        em.flush();
        em.refresh(co);
        
        // Create the Competence Profile
        cp.setCompetenceId(co.getCompetenceId());
        cp.setPersonId(p.getPersonId());
        cp.setYearsOfExperience(ap.getCompetence().get(0).getYearsofExp());
        em.persist(cp);
        em.flush();
        System.out.println(cp.getYearsOfExperience());

       }
       catch(Exception e){System.out.println(e);}
       if(p == null | av == null | co == null | cp == null)
       {
           return false;
       }
       return true;
    }   
    
    /**
     *
     * @param user
     * @param password
     * @return a person object if the user exist
     */
    public PersonDTO getAdmin(String user, String password){
        Query q = em.createQuery("SELECT u FROM Person u WHERE u.username= :user AND u.password =:pass");
        q.setParameter("user","borg");
        q.setParameter("pass", "w19nk23a");
        PersonDTO p;
        p = (Person)q.getSingleResult();
        if(p == null){
                     throw new EntityNotFoundException("No such Availability with id = " + user);
        }
        
        
        return p;
    }
 
    /**
     *
     * @param id 
     * @return a person with the given id
     */
    public PersonDTO findPerson(int id) {  
        PersonDTO p =  em.find(Person.class, id);
        if (p == null) {
            throw new EntityNotFoundException("No such person with id = " + id);
        }
        return p;
    }
   
     /**
     *
     * @param id
     * @return a Availability object with the given id 
     */
    public List <AvailabilityDTO> findAvailability(int id) {
        Query q = em.createQuery("SELECT u FROM Availability u WHERE u.personId= :id");
        q.setParameter("id",id);
        List<AvailabilityDTO> avl;
        
        avl = (List<AvailabilityDTO>)q.getResultList();
        
        if(avl== null){
                     throw new EntityNotFoundException("No such Availability with id = " + id);
        }
        
        
        return avl;
    }
     
     /**
     *
      * @param id
     * @return a CompetenceDTO object with the given id 
     */
    public CompetenceDTO findCompetence(int id) {
        Query q = em.createQuery("SELECT u FROM Competence u WHERE u.competenceId= :id");
        q.setParameter("id",id);
        CompetenceDTO c = (Competence)q.getSingleResult();
        if(c== null){
                     throw new EntityNotFoundException("No such Competence with id = " + id);
        }
        return c;
     
    }
     
     /**
     *
     * @param id
     * @return a CompetenceProfileDTO object with the given id 
     */
    public List<CompetenceProfileDTO> findCompetenceProfile(int id) {
         
        Query q = em.createQuery("SELECT u FROM CompetenceProfile u WHERE u.personId= :id");
        q.setParameter("id",id);        
        List<CompetenceProfileDTO> comp ; 
        comp = (List<CompetenceProfileDTO>)q.getResultList();       
        if(comp == null){
                     throw new EntityNotFoundException("No such Competence with id = " + id);
        }
        return comp;
    }
     
}
 